const program = require("commander");
const { version } = require("./utils/constants"); //获取版本号
// console.log(process.argv);//当前进程的参数  zhu-cli --help运行出结果
// console.log(program)
const path = require("path");

//多个指令命令的集合   运行zhu-cli create xx
const mapAction = {
	create: {
		//创建模板
		alias: "c", //配置命令的别称
		description: "create a project", //命令相对应的描述
		examples: ["zhu-cli create <project-name>"],
	},
	config: {
		//配置文件
		alias: "conf",
		description: "config project variable",
		examples: ["zhu-cli config set <k> <v>", "zhu-cli config get <k>"],
	},
	"*": {
		//根据自己的情况配置别的命令
		alias: "",
		description: "command not found",
		examples: [],
	},
};

//相等于 Object.key() 循环遍历创建命令
Reflect.ownKeys(mapAction).forEach((action) => {
	program
		.command(action) //配置命令的名字
		.alias(mapAction[action].alias) //命令别的名称
		.description(mapAction[action].description) //命令对应的描述
		.action(() => {
			if (action === "*") {
				//访问不到对应的命令 就打印找不到命令
				console.log(mapAction[action].description);
			} else {
				console.log(action);
				//运行zhu-cli create xxx  解析后是[node , zhu-cli  , create  , xxx]
				require(path.resolve(__dirname, action))(
					...process.argv.slice(3)
				);
			}
		});
});
//用户监听help事件打印出信息  运行zhu-cli --help
program.on("--help", () => {
	console.log("\r\nExamples:");
	Reflect.ownKeys(mapAction).forEach((action) => {
		mapAction[action].examples.forEach((example) => {
			console.log("   " + example);
		});
	});
});

//运行zhu-cli --version结果为当前的版本
//解析用户传过来的参数  zhu-cli --help 运行出来结果
program.version(version).parse(process.argv);
